package jinyilw.swing.rlaf.ui;

import jinyilw.swing.graphics.RenderingConfig;
import jinyilw.swing.rlaf.theme.RThemeColor;
import jinyilw.swing.rlaf.utils.RLafUtils;
import jinyilw.swing.visuals.text.JTextCompFunctionListener;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.ScrollPaneUI;
import javax.swing.plaf.basic.BasicTextAreaUI;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;

/**
 * @author Jinyi
 */
public class RTextAreaUI extends BasicTextAreaUI
{
	JTextArea t;
	RFocusManager manager;
	boolean viewportSetted;
	private final RenderingConfig renderingConfig = new RenderingConfig();

	public static ComponentUI createUI(JComponent c)
	{
		return new RTextAreaUI();
	}

	@Override
	public void installUI(JComponent c)
	{
		t = (JTextArea) c;
		super.installUI(c);
		manager = RLafUtils.configTextComponent(t);
		c.setForeground(RThemeColor.colorSet.textColor);
	}

	@Override
	protected void installListeners()
	{
		super.installListeners();
		t.addMouseListener(JTextCompFunctionListener.textCompFunctionListener);
	}

	@Override
	protected void uninstallListeners()
	{
		super.uninstallListeners();
		t.removeMouseListener(
				JTextCompFunctionListener.textCompFunctionListener);
	}

	private void viewportSetting(Graphics g, JComponent c)
	{
		g.setColor(RThemeColor.colorSet.transTBGColor);
		g.fillRect(2, 2, c.getWidth() - 4, c.getHeight() - 4);
		if (!viewportSetted)
		{
			viewportSetted = true;
			Component pc = c.getParent().getParent();
			ScrollPaneUI ui;
			if (pc instanceof JScrollPane && (ui = ((JScrollPane) pc)
					.getUI()) instanceof RScrollPaneUI)
			{
				RScrollPaneUI rUi = (RScrollPaneUI) ui;
				rUi.setFocusManager(manager);
				manager.setPaintComponent(pc);
				rUi.update(g, c);
			}
		}
	}

	@Override
	public void update(Graphics g, JComponent c)
	{
		Graphics2D g2d = (Graphics2D) g;
		Composite composite = g2d.getComposite();
		renderingConfig.setAllAAPainting(g2d);
		if (c.getParent() instanceof JViewport)
			viewportSetting(g, c);
		else
			RLafUtils.paintTextComponent(g, t, manager.isFocus);
		RThemeColor.customTextColorSetting(t);
		paint(g, c);
		renderingConfig.resetAllAAPainting(g2d);
		g2d.setComposite(composite);
	}

	//	@Override
	//	protected void paintSafely(Graphics g)
	//	{
	//		Graphics2D g2d = (Graphics2D) g;
	//		Object savedRenderingHint = g2d
	//				.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
	//		g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
	//				RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	//		super.paintSafely(g);
	//		g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
	//				savedRenderingHint);
	//	}

	@Override
	protected void paintBackground(Graphics g)
	{

	}
}
